package com.cs.cslc.tool.mail.service.Impl;

import com.cs.cslc.tool.mail.service.EmailService;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

/**
 * EmailService 邮件服务.
 *
 * @author cs4380 https://gitee.com/xhbug_cs4380  cs4380@163.com
 * @version 1.0
 * @since 2023-10-10
 */
@Slf4j
@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    private JavaMailSender mailSender;
    /**
     * 发送的邮件账号
     */
    @Value("${spring.mail.username}")
    private String username;

    @Override
    public void sendSimpleMail(String[] to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        // 邮件发送人
        message.setFrom(username);
        // 邮件接收人
        message.setTo(to);
        // 邮件主题 / 邮件标题
        message.setSubject(subject);
        // 邮件内容
        message.setText(content);
        // 发送动作
        mailSender.send(message);
    }

    @Override
    public void sendHtmlMail(String[] to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            // 邮件发送人
            messageHelper.setFrom(username);
            // 邮件接收人
            messageHelper.setTo(to);
            // 邮件主题 / 邮件标题
            messageHelper.setSubject(subject);
            // 邮件内容 , true：使用html
            messageHelper.setText(content, true);
            // 发送动作
            mailSender.send(message);
        } catch (Exception e) {
            log.error("发送邮件失败：to:{},  subject:{},  content:{}. ", to, subject, content, e);
        }
    }

    @Override
    public void sendAttachmentsMail(String[] to, String subject, String content, String filePath) {
        // TODO 发送携带附件的邮件
    }
}
